package fr.uniscol.editors;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.GregorianCalendar;
import java.util.Locale;

public class CustomGregorianCalendarPropertyEditor extends PropertyEditorSupport {

	private DateFormat dateFormat;
	
	public CustomGregorianCalendarPropertyEditor(DateFormat df){
		this.dateFormat = df;
	}
	
	@Override
	public String getAsText() {
		
		if(getValue() == null){
			return null;
		}
		
		GregorianCalendar cal = (GregorianCalendar) getValue();
		
		return dateFormat.format(cal.getTime());
	}

	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		GregorianCalendar cal = new GregorianCalendar(Locale.FRANCE);
		try {
			cal.setTime(dateFormat.parse(text));
			setValue(cal);
			
		} catch (ParseException e) {
			setValue(null);
		}
	}

}
